﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SCZS.Example.Common;

namespace SCZS.Example.Utility
{
    /// <summary>
    /// 全局异常错误
    /// </summary>
    public class GlobalExceptionsFilter: IExceptionFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _logger;
        private string _apiName;
        public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> logger)
        {
            _env = env;
            _logger = logger;
            _apiName = Appsettings.GetValue("Startup:ApiName");
        }

        public void OnException(ExceptionContext context)
        {
            string Method = context.HttpContext.Request.Method.ToUpper();
            string RequestUrl = context.HttpContext.Request.Path;
            dynamic ex = context.Exception;
            string ExName = Convert.ToString(ex.GetType().Name);
            ExName = ExName.ToLower();
            switch (ExName)
            {
                default:
                    _logger.LogError($"{_apiName}->{Method}请求'{RequestUrl}'发生异常:{Convert.ToString(ex.Message)},错误追踪:{Convert.ToString(ex)}");
                    var Result = new ContentResult();
                    Output _output = new Output();
                    _output.IsSuccess = false;
                    _output.ErrorCode = 500;
                    _output.ErrorDomain = _apiName;
                    _output.Message = ex.Message as string;
                    Result.Content = JsonConvert.SerializeObject(_output);
                    context.Result = Result;
                    break;
            }
            context.ExceptionHandled = true;
        }

        public class Output
        {
            string _ErrorDomain;
            /// <summary>
            /// 状态
            /// </summary>
            public bool IsSuccess { get; set; } = true;
            /// <summary>
            /// 消息
            /// </summary>
            public string Message { get; set; }
            /// <summary>
            /// 错误编码
            /// </summary>
            public int? ErrorCode { get; set; } = 0;
            /// <summary>
            /// 错误域
            /// </summary>
            public string ErrorDomain
            {

                get
                {
                    return _ErrorDomain;
                }
                set { this._ErrorDomain = value; }
            }
        }
    }

    
}
